<template>
<!--模糊搜索区域-->
<div>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
    <el-form :inline="true" :model="searchContract"
             label-positio="right" label-width="150px" class="demo-form-inline">
      <el-form-item label="合同编号" prop="contractId" >
        <el-input  v-model="searchContract.contractId" placeholder="请输入合同编号"></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="searchContract.staffName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item style="margin-left: 100px">
        <el-button type="primary" @click="readIn">导入</el-button>
        <el-dialog title="上传计量单位Excel" :visible.sync="dialogExcelVisible" width="40%">
          <!--action:上传到的位置,accept:允许上传的文件类型,multiple:是否允许多文件上传-->
          <el-upload action="http://localhost:8888/sys/contract/upload/excel"
          accept=".xlsx,.xls"
          :on-success="uploadExcelSuccess"
          :on-error="uploadExcelError"
          multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传.xlsx,.xls文件，且不超过500kb</div>
          </el-upload>
        </el-dialog>
        <el-button type="success" @click="writeOut">导出</el-button>
      </el-form-item>
      <br>
      <el-form-item label="身份证号">
        <el-input v-model="searchContract.cardId" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item label="合同类型">
        <el-select v-model="searchContract.contractType" placeholder="请选择合同类型">
          <el-option label="全部类型合同" value="0"></el-option>
          <el-option label="劳务合同" value="1"></el-option>
          <el-option label="派遣合同" value="2"></el-option>
          <el-option label="临时合同" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 100px">
        <el-button type="primary" @click="search" icon="el-icon-search">搜索</el-button>
        <el-button type="info" @click="resetForm('searchContract')" icon="el-icon-refresh">重置</el-button>
        <el-button type="danger" @click="delBatch">批量删除</el-button>
        <el-button type="success" @click="contractAdd">添加</el-button>

        <!--   添加修改对话框     -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible">
          <el-form
            :model="contractInfo"
            label-position="right"
            :rules="contractInfoRules"
            ref="contractInfoRulesForm"
            label-width="120px"
            style="max-width: 500px; margin-left: auto; margin-right: auto;"
          >
            <!-- 使用 el-row 和 el-col 确保每个表单项占据一行 -->
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="姓名" prop="staffName">
                  <el-input v-model="contractInfo.staffName" autocomplete="off" @blur="getCardId()"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item  label="身份证号" prop="cardId">
                  <el-input disabled="disabled" v-model="contractInfo.cardId" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同开始日期" prop="contractStart">
                  <el-date-picker
                    v-model="contractInfo.contractStart"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同结束日期" prop="contractEnd">
                  <el-date-picker
                    v-model="contractInfo.contractEnd"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同类型" prop="contractType">
                  <el-select v-model="contractInfo.contractType" placeholder="请选择">
                    <el-option label="劳务合同" value="1"></el-option>
                    <el-option label="派遣合同" value="2"></el-option>
                    <el-option label="临时合同" value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="派遣公司" prop="staffCompany">
                  <el-select v-model="contractInfo.staffCompany" placeholder="请选择">
                    <el-option label="公司1" value="公司1"></el-option>
                    <el-option label="公司2" value="公司2"></el-option>
                    <el-option label="公司3" value="公司3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否续签" prop="renewState">
                  <el-radio-group v-model="contractInfo.renewState">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm('contractInfoRulesForm')">确 定</el-button>
          </div>
        </el-dialog>
      </el-form-item>
    </el-form>
    </div>

<!-- 表格区域   -->
    <div>
      <template>
        <el-table
          :data="contractList"
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column
            type="selection">
          </el-table-column>
          <el-table-column
            type="index"
            label="序号">
            <template slot-scope="scope">
              {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="contractId"
            label="合同编号"
          width="76">
          </el-table-column>
          <el-table-column
            prop="contractCode"
            label="合同编码"
            width="76">
          </el-table-column>
          <el-table-column
            prop="checkState"
            label="审核状态"
            width="80">
            <template slot-scope="scope">
              <el-tag
                :type="getCheckStateTagType(scope.row.checkState)"
                disable-transitions>
                {{ getCheckStateTagName(scope.row.checkState) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="staffName"
            label="姓名"
            width="50">
          </el-table-column>
          <el-table-column
            prop="cardId"
            label="身份证号"
          width="159">
          </el-table-column>
          <el-table-column
            prop="contractType"
            label="合同类型"
            width="80"
          >
            <template slot-scope="scope">
              <el-tag
                :type="getContractTypeTagType(scope.row.contractType)"
                disable-transitions>
                {{ getContractTypeTagName(scope.row.contractType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="contractStart"
            label="合同开始时间"
            width="165">
          </el-table-column>
          <el-table-column
            prop="contractEnd"
            label="合同结束时间"
          width="165">
          </el-table-column>
          <el-table-column
            prop="staffCompany"
            label="派遣公司"
            width="95">
          </el-table-column>
          <el-table-column
            prop="contractState"
            label="合同状态"
            width="80">
            <template slot-scope="scope">
              <el-tag
                :type="getContractStateTagType(scope.row.contractState)"
                disable-transitions>
                {{ getContractStateTagName(scope.row.contractState) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="renewState"
            label="是否续签"
            width="100">
            <template slot-scope="scope">
              <el-tag
                :type="getRenewStateTagType(scope.row.renewState)"
                disable-transitions>
                {{ getRenewStateTagName(scope.row.renewState) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <!--  scope.row.checkState != '0'代表已审核或不通过 scope.row.contractState != '1'代表未生效或已过期         -->
            <template slot-scope="scope" >
              <el-button
                v-if="scope.row.checkState == '3' "
                type="primary"
                size="mini"
                @click="handleSubmit(scope.row)">提交</el-button>
              <el-button
                v-if="scope.row.checkState != '0' && scope.row.contractState != '1' && scope.row.contractState != '2'"
                size="mini"
                @click="handleEdit(scope.row)">编辑</el-button>
              <el-button
                v-if="scope.row.checkState == '2' || scope.row.checkState == '3' || (scope.row.contractState == '2' && scope.row.renewState == '0')"
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
              <el-button
                v-if="scope.row.checkState == '0'"
                size="mini"
                type="info"
                @click="handleCallback(scope.row)">撤销</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3,5,7,9]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </template>
    </div>
</el-card>
</div>
</template>

<script>
import {
  getContractList,
  del,
  delBatch,
  getCardId,
  addContract,
  update,
  submit, callBack
} from "@/api/contractManage/contractSigning";
import {add} from "script-ext-html-webpack-plugin/lib/custom-attributes";
import {error} from "autoprefixer/lib/utils";
import * as echarts from 'echarts'
export default {
  data() {
    return {
      searchContract:{
        contractId:'', // 合同编号
        staffName:'', // 员工姓名
        cardId:'', // 身份证号
        contractType:'' // 合同类型
      },
      contractList:[],
      ids:[],
      contractStates:[],
      checkState:[],
      total:0,
      pageNum:1,
      pageSize:9,
      dialogFormVisible:false, // 添加/编辑对话框
      dialogExcelVisible:false, // 文件上传对话框
      chartInstance: null, // 如果需要保存 ECharts 实例
      title:'',
      contractInfo:{
        staffName:'', // 姓名
        cardId:'', // 身份证号
        staffId:'', // 员工id
        contractStart:'', // 合同开始日期
        contractEnd:'', // 合同结束日期
        contractType: '', // 合同类型
        staffCompany: '', // 派遣公司
        renewState:'' // 是否续签

      },
      contractInfoRules:{ // 注册校验规则
        staffName:[
          {required:true,message:'姓名不能为空',trigger:'blur'}
        ],
        contractStart:[
          {required:true,message:'合同开始日期不能为空',trigger:'blur'}
        ],
        contractEnd:[
          {required:true,message:'合同结束日期不能为空',trigger:'blur'}
        ],
        contractType:[
          {required:true,message:'合同类型不能为空',trigger:'blur'}
        ],
        staffCompany:[
          {required:true,message:'派遣公司不能为空',trigger:'blur'}
        ]
      },
    }
  },
  methods: {
    onSubmit() {
      console.log('submit!');
    },

    // 上传excel文件成功
    uploadExcelSuccess(res, file) {
      this.$message.success("上传成功");
      this.dialogExcelVisible = false;
      this.getContractList()
    },
    // 上传excel文件失败
    uploadExcelError(err, file) {
      this.$message.error("上传失败");
      console.log("上传失败", err);
      this.excelDialogVisible = false;
    },

    // 导入按钮事件
    readIn(){
      this.dialogExcelVisible = true
    },

    // 导出按钮事件
    writeOut(){
      window.location.href = "http://127.0.0.1:8888/sys/contract/export/excel"
    },

    // 提交按钮事件
    handleSubmit(row){
      submit({
        contractId:row.contractId
      }).then(res=>{
        if (res.code === 20000){
          this.$message.success("提交成功")
          this.pageNum =1
          this.getContractList()
        }
      })
    },

    // 撤销按钮事件
    handleCallback(row){
      callBack({
        contractId:row.contractId
      }).then(res=>{
        if (res.code === 20000){
          this.$message.success("撤销成功")
          this.pageNum = 1
          this.getContractList()
        }
      })
    },



    // 添加时根据输入的名字查找对应的员工信息
    getCardId(){
      getCardId({
        staffName:this.contractInfo.staffName
      }).then(res=>{
        if (res.code === 20000){
          this.contractInfo.cardId = res.data.cardId
          this.contractInfo.staffId = res.data.staffId
        }
      }).catch(error=>{
        this.contractInfo.staffName=''
      })
    },

    // 添加更新选择功能
    submitForm(formName){
      this.$refs[formName].validate((valid)=>{
        if (valid){
          // 这是符合规则,判断执行添加还是修改
          if (this.title === "添加合同"){
            if(this.contractInfo.contractStart > this.contractInfo.contractEnd){
              this.$message.error("合同结束日期在合同开始日期之前,不符合规则,重新添加")
              this. contractAdd()
            }else {
              addContract(this.contractInfo).then(res=>{
                if(res.code === 20000){
                  this.$message.success("添加成功")
                }
              }).catch(error=>{
              })
            }
            }
           else if (this.title === "修改合同"){
            update(this.contractInfo).then(res=>{
              if (res.code === 20000){
                this.$message.success("更新成功")
              }
            })
          }
          this.dialogFormVisible = false
          this.pageNum = 1
          this.getContractList()
        }
      })
    },
    /**
     * 打开添加对话框
     */
    contractAdd(){
      this.title="添加合同"
      this.dialogFormVisible = true
      this.contractInfo = {}
    },

    /**
     * 打开编辑对话框
     */
    handleEdit(row){
      this.title="修改合同"
      this.dialogFormVisible = true
      this.contractInfo = row
    },

    // 判断是否需要续签
    getRenewStateTagType(status){
      const typeMap={
        '0':'info',
        '1':'primary'
      }
      return typeMap[status] || '';
    },

    // 续签类型前端展示
    getRenewStateTagName(status){
      const typeMap={
        '0':'不续签',
        '1':'续签'
      }
      return typeMap[status] || '';
    },

    // 判断审批类型
    getCheckStateTagType(status) {
      const typeMap = {
        '0': 'info',
        '1': 'success',
        '2': 'warning',
        '3': 'primary',
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },
    // 审批类型前端展示
    getCheckStateTagName(status) {
      const typeMap = {
        '0': '待审核',
        '1': '已通过',
        '2': '未通过',
        '3': '待提交',
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },

    // 判断合同类型
    getContractTypeTagType(status) {
      const typeMap = {
        '1': 'info',
        '2': 'success',
        '3': 'primary'
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },
    // 合同类型前端展示
    getContractTypeTagName(status) {
      const typeMap = {
        '1': '劳务合同',
        '2': '派遣合同',
        '3': '临时合同'
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },

    // 判断合同状态
    getContractStateTagType(status) {
      const typeMap = {
        '0': '',
        '1': 'success',
        '2': 'warning'
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },
    // 合同状态前端展示
    getContractStateTagName(status) {
      const nameMap = {
        '0': '未开始',
        '1': '生效中',
        '2': '已到期'
      };
      return nameMap[status] || '未知'; // 如果状态不在预期范围内，则返回'未知'
    },


    /**
     * 复选框改变
     */
    handleSelectionChange(val){
      const contractStates =[]
      const ids =[]
      const checkState=[]
      for (let i = 0;i<val.length;i++){
        ids.push(val[i].contractId)
        contractStates.push(val[i].contractState)
        checkState.push(val[i].checkState)
      }
      this.checkState = checkState
      this.contractStates = contractStates
      this.ids = ids

    },

    /**
     * 查询所有合同
     */
    getContractList(){
      console.log(this.searchContract.contractType)
      getContractList({
        pageNum:this.pageNum,
        pageSize:this.pageSize,
        contractId: this.searchContract.contractId,
        staffName: this.searchContract.staffName,
        cardId: this.searchContract.cardId,
        contractType: this.searchContract.contractType
      }).then(res=>{
        console.log("查询全部",this.contractList)
        if (res.code === 20000){
          this.contractList = res.data.list
          this.total = res.data.total
        }
      })
    },

    /**
     * 模糊查询
     */
    search(){
      this.getContractList()
    },



    /**
     * 删除单条合同信息
     */
    handleDelete(row){
      this.$confirm("是否要删除本条数据","提示",{
        confirmButtonText:"确认",
        cancelButtonText:"取消"
      }).then(()=>{
        del({
          contractId:row.contractId
        }).then(res=>{
          if (res.code === 20000){
            this.$message.success("删除成功")
          }
          this.pageNum =1
          this.getContractList()
        })
      }).catch(()=>{
        this.$message.info("取消删除")
      })
    },
    /**
     * 改变当前页
     */
    handleCurrentChange(val){
      this.pageNum = val
      this.getContractList()
    },


    /**
     * 批量删除
     */
    delBatch(){
      if (this.ids.length <=0){
        this.$message.warning("未选择删除数据,无法执行")
      }else{
        for (let i = 0;i<this.contractStates.length;i++) {
          if (this.contractStates[i] === 1 ||this.checkState[i] === 0) {
            this.$message.warning("选择的数据不能删除(待审核,生效期的数据无法删除),重新选择")
            this.getContractList()
            return;
          }
        }
        this.$confirm("是否删除所选择的数据","提示",{
          confirmButtonText:'确定',
          cancelButtonText:'取消'
        }).then(()=>{
          delBatch({
            ids:this.ids.join(",")
          }).then(res=>{
            if (res.code === 20000){
              this.$message.success("删除成功")
            }
            this.pageNum = 1
            this.getContractList()
          })
        }).catch(()=>{
          this.$message.info("取消删除")
        })

      }
    },



    /**
     * 改变每页展示行数
     */
    handleSizeChange(val){
      this.pageSize = val
      this.getContractList()
    },

    /**
     * 重置按钮
     */
    resetForm(formName){
      this.searchContract= {}
    }
    },
  created() {
    this.getContractList()
  },
}
</script>

<style scoped lang="scss">
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: auto;
}
.el-input{
  width: 300px;
}
.el-select{
  width: 300px;
}
</style>
